
export default class Count {

  constructor() {

    this.xyxid = 'gaonengyouxi';
    this.uri = 'https://xiaoyouxi.coco.cn';
    this.cfg = {};
    this.openid = 'undefined';
    this.getShareInfo();
  }

  
  setEnv(cfg) {
    console.log('-------getLaunchOptionsSync1111---------');
    this.cfg = cfg;
  }

  setOpenid(openid) {
    this.openid = openid;
  }

  //拉取渠道映射表
  eventReady(callable) {
    var _this = this;


    var returnEvent = function(ch) {
      return callable(ch);
    };

    wx.getStorage({
      key: 'channel',
      success(res) {
        // console.log('---------mapping load');
        // console.log(res.data);
        returnEvent(res.data.id);
      },

      fail(res) {
        wx.request({
          url: _this.uri + '/Server/GameCenter/channel',
          success(res) {
            if (res.data.code == 0) {
              // console.log(res.data.result);
              var ch = _this.getSourceChannel();

              // console.log('getSourceChannel : ' + ch);

              var chinfo = {};
              chinfo = res.data.result[ch];
              if (chinfo != undefined) {
                chinfo.key = ch;
              } else {
                var chinfo = {};
                chinfo.id = "000000";
                chinfo.key = ch;
                chinfo.tip = ch;
              }

              // console.log(chinfo);
              wx.setStorage({
                key: 'channel',
                data: {
                  id: chinfo['id'],
                  key: chinfo['key'],
                  tip: chinfo['tip']
                },
                success() {
                  returnEvent(chinfo.id);
                }
              })
            } else {
              console.log('[ERROR] gameCenter/channel api ');
            }
          }
        })

      }

    })

  }


  GetRequest(str) {
    var theRequest = new Object();
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
    return theRequest;
  }

  getSourceChannel() {
    var ch = 'default';
    // console.log(this.cfg);
    try {
      //扫码场景
      if (this.cfg.query.scene) {
        var scene = decodeURIComponent(this.cfg.query.scene);
        // console.log(scene);
        var request = this.GetRequest(scene);
        // console.log(request);
        ch = request['cksrc'];
        return ch;
      }

    } catch (exception) {
      // console.log('-----not scan qrcode');
      //console.log(exception);
    }

    try {
      if (this.cfg.referrerInfo.appId != undefined) {
        return this.cfg.referrerInfo.appId;
      }
    } catch (exception) {
      console.log('-----not from appid');
    }


    try {
      if (this.cfg.query.cksrc != undefined) {
        return this.cfg.query.cksrc;
      }
    } catch (exception) {
      console.log('-----not from launch params');
    }

    console.log('ch is :' + ch);
    return ch;
  }


  beginTime() {
    var tmp = Date.parse(new Date()).toString();
    tmp = tmp.substr(0, 10);
    wx.setStorage({
      key: 'start_time',
      data: tmp,
      success(res) {
        console.log('start_time: ' + tmp);
      }
    });
  }


  stopTime() {
    var _this = this;
    wx.getStorage({
      key: 'start_time',
      success(res) {
        var tmp = Date.parse(new Date()).toString();
        tmp = tmp.substr(0, 10);
        var second = tmp - res.data;
        console.log('当前会话停留时间 :' + second);

        _this.request('time', { second: second });
      }
    });
  }



  /**
   * 点击分享或者 从分享页面进入统计
   * event (share 打开页面  enter  从分享页面进入)
   * sharemid (分享的参数  ShareMessage/index 接口返回的 id参数)
   */
  shareMessage(event, sharemid) {
    this.request('shareMessage', { 
      share_event: event,
      sharemid: sharemid
    });
  }



  newUserCount() {
    this.request('newUser');
  }


//获取分享文案
  getShareInfo(){
    var _this = this;
    var data = {
      'xyxid' : this.xyxid,
    };
    wx.request({
      url: _this.uri + '/Server/ShareMessage/index',
      data: data,
      success(res){
        var data = res.data.result;
        wx.setStorage({
          key: 'shareInfo',
          data: data,
        })
        console.log("shareInfo saved");
      },
    })
  }



  request(logtype, params) {
    var _this = this;
    wx.getStorage({
      key: 'channel',
      success: function(res) {
        console.log('channel_info:');
        console.log(res);
        var data = {
          xyxid: _this.xyxid,
          ckhsrc: res.data.key,
          chhsrc_name: res.data.tip + '(' + res.data.id + ')',
          logtype: logtype,
          openid: _this.openid,
          query: _this.cfg.query,
          scene: _this.cfg.scene
        };

        if (typeof params == "object"){
          data = Object.assign(data, params);
        }
        wx.request({
          url: _this.uri + '/Server/GameCenter/logRecord',
          data: data
        })

      },
    })
  }

  /**
    * 页面点击位置分享
    * unitName (hot 热门  discover 发现 test  测一测)
    * unitPos (位置索引 0 1 2 3 4 5 6 以此类推)
    * appid 点击的游戏或小程序appid
    */
  unitCount(unitName, unitPos, appid) {
    this.request('unitCount', {
      unit_name: unitName,
      unit_pos: 'pos_' + unitPos,
      unit_appid: appid
    });
  }

  /**
    * 点击转盘
    * action (enter 进入转盘页面  click 点击抽奖按钮)
    * item (点击转盘获得的奖励 例如 coin_50)
    */
  whellSurfCount(action, item = '') {
    this.request('whellSurfCount', {
      action: action,
      itme: item
    });
  }

}